<template>
  <ElUpload accept=".jpg,.jpeg,.png,.icon" :before-upload="onBeforeUpload" class="full">
    <div class="box">
      <span v-if="!src" class="font-size-30px color-[var(--el-border-color)]">+</span>
      <div v-else class="image-box" @mouseover="onMouseOver" @mouseout="onMouseOut">
        <img :src="src" class="image" />
        <el-icon v-show="showBadge" class="badge" @click.stop="remove"><Close /></el-icon>
      </div>
    </div>
  </ElUpload>
</template>
<script setup lang="ts">
  import { isNumber } from 'lodash-es'
  import { ElUpload, UploadRawFile, ElIcon } from 'element-plus';
  import { Close } from '@element-plus/icons-vue';
  import { computed, ref, watch } from 'vue';
import feedback from '@/utils/feedback';

  const props = defineProps<{width?: string|number,height?: string|number, maxSize?: number, modelValue?: string}>()
  const emits = defineEmits(['update:modelValue'])

  const maxSize = props.maxSize || 9999
  const width = computed(() => {
    if(!props.width) return '50px'
    return isNumber(props.width) ? `${props.width}px` : props.width
  })
  const height = computed(() => {
    if(!props.height) return '50px'
    return isNumber(props.height) ? `${props.height}px` : props.height
  })

  const src = ref<string>(props.modelValue)
  function onBeforeUpload(file: UploadRawFile) {
    if(file.size > maxSize) {
      feedback.alertError(`文件不能超过【${maxSize}】字节`)
      return false
    }

    var reader = new FileReader()
    reader.onload = (e) => src.value = e.target.result as string
    reader.readAsDataURL(file)
    return false
  }

  const showBadge = ref(false)
  const onMouseOver = () => showBadge.value = true
  const onMouseOut = () => showBadge.value = false

  function remove() {
    src.value = void 0
  }

  watch(() => props.modelValue, () => src.value = props.modelValue)
  watch(src, (val) => emits('update:modelValue', val))
</script>
<style lang="less" scoped>
  .box {
    display: flex;
    justify-content: center;
    align-items: center;
    border: 1px dashed var(--el-border-color);
    border-radius: 2px;
    width: v-bind(width);
    height: v-bind(height);

    &:hover {
      border-color: #409EFF;
    }
  }
  .image {
    max-width: 100%;
    max-height: 100%;
  }

  .image-box {
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;

    .badge {
      position: absolute;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 25px;
      height: 25px;
      top: 0;
      right: 0;
      background-color: #409EFF; /* 角标背景颜色 */
      color: white; /* 角标文字颜色 */
      border-radius: 50%; /* 使角标圆角 */
      transform: translate(50%, -50%); /* 调整位置使其完全在右上角 */
    }
  }
</style>